import { User } from '@/AGC/model/User'
import {
  executeDeleteFoodCollect,
  executeUpsert,
  executeUpsertFoodCollect,
  queryFoodCollect,
  queryFoodCollectSingle,
  queryUser,
} from '@/AGC/manager/user'
import { FoodCollect } from '@/AGC/model/FoodCollect'
import type { UserI } from '@/types/user'
import { useUserStore } from '@/stores/user'
import { ElMessage, type UploadFile } from 'element-plus'
import { CLOUD_STORAGE_PATH } from '@/constants'
import { createStoragePerference, reference } from '@/AGC/manager'
import {
  executeDeleteAllExerciseRecord,
  executeDeleteAllFoodRecord,
  executeDeleteAllWeightRecord,
} from '../manager/record'
import { executeDeleteFoodPlan, executeDeleteFoodPlanByDate } from '../manager/food_plan'
import {
  executeDeleteExercisePlan,
  executeDeleteExercisePlanByDate,
} from '../manager/exercise_plan'
import dayjs from 'dayjs'
/**
 * 创建用户
 * @param token 用户令牌
 */
export const createUser = async (token: string) => {
  // 创建用户
  const user = new User()
  user.setToken(token)
  const digit = Math.floor(Math.random() * 1000)
  user.setNickname(`康途${digit}`)

  // 执行插入
  const result = await getUserInfo(token)

  if (!result) {
    await executeUpsert(user)
  }
}

/**
 * 获取用户信息
 * @param token 用户令牌
 * @returns 用户信息
 */
export const getUserInfo = async (token: string) => {
  // 查询用户
  const result = await queryUser(token)

  if (result.length > 0) {
    const user = result[0]

    return {
      id: user.getId()!,
      nickname: user.getNickname(),
      phone: user.getPhone()!,
      email: user.getEmail()!,
      sex: user.getSex()!,
      age: user.getAge()!,
      height: user.getHeight()!,
      weight: user.getWeight()!,
      token: user.getToken(),
      avatar: user.getAvatar()!,
    }
  }
}

/**
 * 更新用户信息
 * @param userI 用户信息
 */
export const updateUser = async (userI: UserI) => {
  // 创建 User 对象
  const user = new User()
  const userStore = useUserStore()

  user.setId(userStore.userInfo.id)
  user.setToken(userStore.token)
  user.setAvatar(userStore.userInfo.avatar)
  user.setNickname(userI.nickname)
  user.setPhone(userI.phone)
  user.setEmail(userI.email)
  user.setSex(userI.sex)
  user.setAge(userI.age)
  user.setHeight(userI.height)
  user.setWeight(userI.weight)

  // 执行插入
  await executeUpsert(user)
}

/**
 * 获取用户收藏的食物ids
 * @param user_id 用户id
 * @returns 用户收藏的食物ids
 */
export const getFoodCollectIds = async (user_id: number) => {
  const result = await queryFoodCollect(user_id)
  return result.map((item) => item.getFood_id())
}

/**
 * 创建用户收藏食物
 * @param food_id 食物id
 */
export const createFoodCollectUtil = async (food_id: number) => {
  const userStore = useUserStore()
  const user_id = userStore.userInfo.id

  const foodCollect = new FoodCollect()
  foodCollect.setUser_id(user_id)
  foodCollect.setFood_id(food_id)

  await executeUpsertFoodCollect(foodCollect)
}

/**
 * 删除用户收藏食物
 * @param id 用户收藏食物id
 */
export const deleteFoodCollectUtil = async (food_id: number) => {
  const userStore = useUserStore()
  const user_id = userStore.userInfo.id

  const result = await queryFoodCollectSingle(user_id, food_id)

  await executeDeleteFoodCollect(result)
}

/**
 * 上传用户头像
 * @param file 头像
 */
export const uploadAvatarUtil = (file: UploadFile) => {
  if (!reference) createStoragePerference()

  const path = CLOUD_STORAGE_PATH + file.name
  const uploadTask = reference.child(path).put(file.raw!)

  uploadTask.on(
    'state_changed',
    () => {},
    (error: Error) => {
      ElMessage.error('上传失败')
      Promise.reject(error)
    },
    async () => {
      try {
        const store = useUserStore()
        store.userInfo.avatar = file.name
        await updateUser(store.userInfo)
        ElMessage.success('上传成功')
      } catch (error) {
        Promise.reject('上传失败')
        Promise.reject(error)
      }
    },
  )
}

/**
 * 用户头像下载地址
 * @returns 头像下载地址
 */
export const downloadAvatarUtil = async () => {
  if (!reference) createStoragePerference()

  const avatar = useUserStore().userInfo.avatar

  if (avatar) {
    const path = CLOUD_STORAGE_PATH + avatar
    return await reference.child(path).getDownloadURL()
  }
}

/**
 * 清除用户的所有数据
 */
export const executeDeleteAllData = async () => {
  await executeDeleteAllFoodRecord()
  await executeDeleteAllExerciseRecord()
  await executeDeleteAllWeightRecord()
  await executeDeleteFoodPlan()
  await executeDeleteExercisePlan()
}

/** 清除当天之后的计划 */
export const executeDeletePlanByDate = async () => {
  const dateString = dayjs().format('YYYY-MM-DD')
  await executeDeleteFoodPlanByDate(dateString)
  await executeDeleteExercisePlanByDate(dateString)
}
